package com.sjft.cloud.commons.core.utils;

import com.sjft.cloud.commons.core.constant.Constant;
import com.sjft.cloud.commons.core.tree.TreeNode;
import lombok.experimental.UtilityClass;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * TreeUtils
 *
 * @author Jin
 */
@UtilityClass
public class TreeUtils {

    /**
     * list to tree
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends TreeNode> List<T> toTree(List<T> list) {
        //返回的节点树
        List<T> rootNodes = new ArrayList<>();
        Iterator<T> it = list.iterator();
        while (it.hasNext()) {
            T next = it.next();
            //parent（上级Id）为0的是根节点
            if (Constant.ZERO.toString().equals(next.getParentNodeId().toString())) {
                rootNodes.add(next);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (T secondNode : rootNodes) {
            List<T> child = getChild(list, secondNode.getCurrentNodeId());
            secondNode.setChildren(child);
        }
        return rootNodes;

    }

    /**
     * 查子节点
     *
     * @param list
     * @param parentId
     * @param <T>
     * @return
     */
    private static <T extends TreeNode> List<T> getChild(List<T> list, Serializable parentId) {

        //子节点列表
        List<T> childList = new ArrayList<>();
        Iterator<T> it = list.iterator();
        while (it.hasNext()) {
            T node = it.next();
            if (parentId.toString().equals(node.getParentNodeId().toString())) {
                childList.add(node);
                it.remove();
            }
        }

        //遍历 递归获取子节点的子节点
        for (T childNode : childList) {
            List<T> child = getChild(list, childNode.getCurrentNodeId());
            childNode.setChildren(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

}
